package org.sixtynine.stock.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.sixtynine.stock.dto.GridPramDTO;
import org.sixtynine.stock.dto.Page;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.PackageData;
import org.sixtynine.stock.entity.User;
import org.sixtynine.stock.entity.UserCategory;
import org.sixtynine.stock.model.LoadingSearchCriteria;
import org.sixtynine.stock.service.GenericService;
import org.sixtynine.stock.service.PackageDataService;
import org.sixtynine.stock.service.UserCategoryService;
import org.sixtynine.stock.service.content.DataManagerService;
import org.sixtynine.stock.service.file.FileDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Thilan
 * 
 *         this class use to add , edit and delete package data
 * 
 */

@Controller
@SessionAttributes
public class PackageController extends BackEndAuthController {

	/** TODO configure */
	private int RECORDS_PER_PAGE = 10;

	@Autowired
	private GenericService genericService;

	@Autowired
	private FileDataService fileDataService;

	@Autowired
	DataManagerService dataManagerService;

	@Autowired
	PackageDataService packageDataService;

	@Autowired
	UserCategoryService userCategoryService;

	@RequestMapping(value = "/admin/package_data/search")
	public ModelAndView search(@ModelAttribute LoadingSearchCriteria criteria) {
		ModelAndView modelAndView = new ModelAndView("/admin/package_data/list");
		loadData(1, -1, criteria.getName(), criteria.getDuration(),
				modelAndView, criteria);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/package_data/add")
	public ModelAndView addPackage(HttpServletRequest request) {
		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}

		List<BaseEntity> userCategoryList = genericService
				.findAll(UserCategory.class);

		modelAndView = new ModelAndView("/admin/package_data/add");
		modelAndView.addObject("packageData", new PackageData());
		modelAndView.addObject("userCategoryMap", userCategoryList);
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/package_data/add/process")
	public ModelAndView addingPackage(
			@ModelAttribute @Valid PackageData packageData, BindingResult result) {

		ModelAndView modelAndView = null;
		if (!result.hasErrors()) {
			genericService.saveOrUpdate(packageData);
			modelAndView = new ModelAndView("/admin/package_data/list");

			loadData(1, -1, null, -1, modelAndView, null);
			modelAndView.addObject("userLogged", true);
			return modelAndView;
		} else {
			modelAndView = new ModelAndView("/admin/package_data/add");
			modelAndView.addObject("packageData", new PackageData());
			modelAndView.addObject("userLogged", true);
			return modelAndView;
		}

	}

	@RequestMapping(value = "/admin/package_data/list")
	public ModelAndView listOfPackage(
			HttpServletRequest request,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "totalRecords", required = false) Integer totalRecords) {

		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/package_data/list");
		loadData(page, totalRecords, null, -1, modelAndView, null);
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	/**
	 * load data
	 * 
	 * @param page
	 * @param totalRecords
	 * @param companyId
	 * @param fromDate
	 * @param toDate
	 * @param modelAndView
	 */
	private void loadData(Integer page, Integer totalRecords, String name,
			int duration, ModelAndView modelAndView,
			LoadingSearchCriteria criteria) {
		GridPramDTO gridPramDTO = new GridPramDTO();
		gridPramDTO.setRows(RECORDS_PER_PAGE);
		if (page != null) {
			gridPramDTO.setPage(page);
		} else {
			gridPramDTO.setPage(1);
		}
		if (totalRecords != null) {
			gridPramDTO._setTotalNumberOfRecords(totalRecords);
		}

		Page<PackageData> packageDataPage = packageDataService
				.searchPackageData(duration, name, "duration", "name",
						gridPramDTO);
		modelAndView.addObject("packageDataPage", packageDataPage);

		if (criteria == null) {
			criteria = new LoadingSearchCriteria();
			criteria.setName(name);

		}
		modelAndView.addObject("criteria", criteria);

	}

	@RequestMapping(value = "/admin/package_data/edit/{id}", method = RequestMethod.GET)
	public ModelAndView editPackageData(HttpServletRequest request,
			@PathVariable Integer id) {
		ModelAndView modelAndView = null;

		if (!isUserLogged(request)) {
			modelAndView = new ModelAndView("/login/login");
			modelAndView.addObject("registedUser", new User());
			return modelAndView;
		}
		modelAndView = new ModelAndView("/admin/package_data/edit");
		BaseEntity packageData = genericService.findById(id, PackageData.class);
		List<BaseEntity> userCategoryList = genericService
				.findAll(UserCategory.class);
		modelAndView.addObject("userCategoryMap", userCategoryList);

		modelAndView.addObject("packageData", packageData);
		modelAndView.addObject("userLogged", true);

		return modelAndView;
	}

	@RequestMapping(value = "/admin/package_data/edit/{id}", method = RequestMethod.POST)
	public ModelAndView edditingPackageData(
			@ModelAttribute @Valid PackageData packageData,
			BindingResult result, @PathVariable Integer id) {

		if (!result.hasErrors()) {
			genericService.saveOrUpdate(packageData);

			ModelAndView modelAndView = new ModelAndView(
					"/admin/package_data/list");

			List<BaseEntity> packages = genericService
					.findAll(PackageData.class);
			modelAndView.addObject("packages", packages);

			loadData(1, -1, packageData.getName(), packageData.getDuration(),
					modelAndView, null);

			String message = "Package Data was successfully edited.";
			modelAndView.addObject("message", message);

			return modelAndView;
		} else {
			ModelAndView modelAndView = new ModelAndView(
					"/admin/package_data/edit");
			return modelAndView;
		}
	}

	@RequestMapping(value = "/admin/package_data/delete/{id}", method = RequestMethod.GET)
	public ModelAndView deletePackageData(@PathVariable Integer id) {
		genericService.delete(id, PackageData.class);

		ModelAndView modelAndView = new ModelAndView("/admin/package_data/list");

		loadData(1, -1, null, -1, modelAndView, null);

		String message = "Package Data was successfully deleted.";
		modelAndView.addObject("message", message);
		return modelAndView;
	}
}
